package common.test;

import common.ListNode;

/**
 * 23. 合并 K 个升序链表
 */
public class _23_MergeKLists {

    public ListNode mergeKLists(ListNode[] lists) {
        if (lists == null || lists.length == 0) {
            return null;
        }

        return merge(0, lists.length - 1, lists);
    }

    public ListNode merge(int i, int j, ListNode[] lists) {
        if (i == j) {
            return lists[i];
        }
        if (i > j) {
            return null;
        }
        int mid = (i + j) / 2;
        return merge(merge(i, mid, lists), merge(mid + 1, j, lists));
    }


    public ListNode merge(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode head = new ListNode(0);
        ListNode tail = head;
        while (l1 != null && l2 != null) {
            if (l1.val > l2.val) {
                tail.next = l2;
                l2 = l2.next;
            } else {
                tail.next = l1;
                l1 = l1.next;
            }
            tail = tail.next;
        }
        tail.next = l1 == null ? l2 : l1;
        return head.next;
    }
}
